package com.zlyx.easy.database.supports;

import java.lang.reflect.Field;

import com.zlyx.easy.core.map.SafeMap;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.SpringUtils;
import com.zlyx.easy.database.annotations.ForeignKey;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月9日 下午7:17:31
 */
public class SqlHelper {

	private static SafeMap<Field> keys = SafeMap.newMap();
	
	public static Field getForeginKey(Class<?> mainTable, String tableName) {
		String keyName = mainTable.getSimpleName() +"&&"+ tableName;
		Class<?> table = SpringUtils.getBean(tableName).getClass();
		Field key = keys.get(keyName);
		if(ObjectUtils.isEmpty(key)) {
			Field[] fields = mainTable.getDeclaredFields();
			ForeignKey foreignKey = null;
			for(Field field : fields) {
				foreignKey = field.getAnnotation(ForeignKey.class);
				if(foreignKey != null && table == foreignKey.table()) {
					keys.put(keyName, field);
					return field;
				}
			}
		}
		return key;
	}
}
